//
//  ImageListViewController.m
//  reacticons
//
//  Created by Admin on 6/20/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ImageListViewController.h"
#import "DataManagement.h"
#import "AppDelegate.h"
#import "ImageDetailViewController.h"
#import "UIGridViewCell+DownloadImage.h"
#import "Utilities.h"
#import "TestFlight.h"
#import "DownloadHelper.h"
#import "MemeCreatorViewController.h"
#import <QuartzCore/QuartzCore.h>
#define STARTING_SAVE_MULTIPLE  1
#define CANCEL_SAVE_MULTIPLE    2
#define CONFIRM_SAVE_MULTIPLE   3

@interface ImageListViewController (internal)

- (UIImage *)imageAtIndex:(NSUInteger)index;
- (void)popupDidSelectBtnTag:(int)tag;

@end

@implementation ImageListViewController

@synthesize parentID = _parentID;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidLoad
{
    [super viewDidLoad];

    [saveMultiToolBar setHidden:YES];
    [saveMultiToolBar setFrame:CGRectMake(0, 0, 320, 44)];

    
    UIBarButtonItem * saveMultiple = [[UIBarButtonItem alloc] initWithTitle:@"Select" 
                                                                      style:UIBarButtonItemStyleBordered 
                                                                     target:self 
                                                                     action:@selector(btnWasClicked:)];
    saveMultiple.tag=STARTING_SAVE_MULTIPLE;
    
    [self.navigationItem setRightBarButtonItem:saveMultiple];
    
    isMultipleSelection = NO;
    
    [saveMultiple release];
    NSLog(@"parentID:%@",_parentID);
    if (![_parentID isEqualToString:@"recentlyAdded"]
        &&![_parentID isEqualToString:@"recentlyUsed"]) 
    {
        imageListArray = [[[(AppDelegate*)[[UIApplication sharedApplication]delegate] dataManager] readItemsFromEntity:@"ManagedItems" WithName:nil AndType:@"item" AndParentID:[_parentID lowercaseString]] retain];

    }
    else {
        imageListArray=[[[(AppDelegate*)[[UIApplication sharedApplication] delegate] dataManager] readRecentlyItemsWithType:_parentID] retain];
        NSLog(@"imagelistarray:%d",imageListArray.count);
        if ([_parentID isEqualToString:@"recentlyUsed"]) {
            self.navigationItem.rightBarButtonItem.title=@"Clear";
        }
    }
    
    NSLog(@"%d",imageListArray.count);
    listOfFlags = [[NSMutableArray alloc] init];
    
    for (int i = 0; i < imageListArray.count; i++)
        [listOfFlags addObject:@"0"];
    
    gridView = [[UIGridView alloc] initWithFrame:CGRectMake(0, 0, 320, 368)];
    [gridView setBackgroundColor:[UIColor blackColor]];
    gridView.delegate=self;
    gridView.dataSource=self;
    
    [gridView setAutoresizingMask:UIViewAutoresizingNone];
    [gridView setEnableMultipleSelection:NO];
    [gridView setEnableReOrderring:NO];
    [self.view insertSubview:gridView atIndex:0];

    popUpBar = [[PopUpViewController alloc] init];
    [popUpBar.view setFrame:CGRectMake(0, 0, 72, 34)];
    [popUpBar.view setHidden:YES];
    [popUpBar setDelegate:self];
    [self.view addSubview:popUpBar.view];
    
    //
    //popup label
    popupLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 40)];
    [popupLabel setText:@"Image Copied!"];
    [popupLabel setFont:[UIFont fontWithName:@"Helvetica" size:14]];
    [popupLabel setTextColor:[UIColor whiteColor]];
    [popupLabel setTextAlignment:UITextAlignmentCenter];
    [popupLabel setBackgroundColor:[UIColor blackColor]];
    popupLabel.layer.borderColor=[UIColor whiteColor].CGColor;
    popupLabel.layer.borderWidth=2;
    popupLabel.layer.cornerRadius=10;
    [popupLabel setHidden:YES];
    [self.view addSubview:popupLabel];
    [popupLabel setCenter:CGPointMake(self.view.center.x, self.view.center.y+100)];
    
    //


}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [gridView reloadData];
    [popUpBar.view setHidden:YES];
}

- (void)viewDidUnload
{
    [[(AppDelegate*)[[UIApplication sharedApplication] delegate] appQueue] cancelAllOperations];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(IBAction)btnWasClicked:(id)sender{
    //save multiple =1
    UIBarButtonItem * barButton = sender;
    [popUpBar.view setHidden:YES];
    switch (barButton.tag) 
    {
        case STARTING_SAVE_MULTIPLE:
            isDownloadedByPopup=NO;
//            if ([_parentID isEqualToString:@"recentlyAdded"]) {
//                for (Items *item in imageListArray) {
//                    [item setField4:@"19990102030405"];
//                    [[(AppDelegate*)[[UIApplication sharedApplication] delegate] dataManager] updateAnItem:item inEntityWithName:@"ManagedItems"];
//                }
//                imageListArray=[[[(AppDelegate*)[[UIApplication sharedApplication] delegate] dataManager] readRecentlyItemsWithType:_parentID] retain];
//                [gridView reloadData];
//                return;
//            }
//            else  
            if ([_parentID isEqualToString:@"recentlyUsed"]){
                for (Items *item in imageListArray) {
                    [item setField5:@"19990102030405"];
                    [[(AppDelegate*)[[UIApplication sharedApplication] delegate] dataManager] updateAnItem:item inEntityWithName:@"ManagedItems"];
                }
                imageListArray=[[[(AppDelegate*)[[UIApplication sharedApplication] delegate] dataManager] readRecentlyItemsWithType:_parentID] retain];
                [gridView reloadData];
                return;
            }
            [saveBtn setEnabled:NO];
            if (!listSelected) {
                listSelected=[[NSMutableArray alloc] init];
            }
            [gridView setFrame:CGRectMake(0, 44, 320, 368)];
            [listSelected removeAllObjects];
            isMultipleSelection = YES;
            [gridView setEnableMultipleSelection:YES];
            [self.navigationController setNavigationBarHidden:YES animated:NO];
            [saveMultiToolBar setHidden:NO];
            break;
            
        case CANCEL_SAVE_MULTIPLE:
            [gridView setFrame:CGRectMake(0, 0, 320, 368)];        
            [self.navigationController setNavigationBarHidden:NO animated:NO];
            [saveMultiToolBar setHidden:YES];
            isMultipleSelection = NO;
            [gridView setEnableMultipleSelection:NO];
            for (NSNumber * index in listSelected) {
                [[gridView cellAtIndex:[index intValue]] setIsSelected:NO];
            }
            for (int i = 0; i < imageListArray.count; i++)
                [listOfFlags addObject:@"0"];
            
            [gridView reloadData];
            [TestFlight passCheckpoint:@"Cancel to Save Multiple"];
            break;
            
        case CONFIRM_SAVE_MULTIPLE:
            
            [[(AppDelegate*)[[UIApplication sharedApplication] delegate] loadingView] showLoadingView];
            isMultipleSelection = NO;
            [gridView setEnableMultipleSelection:NO];
            [barButton setEnabled:NO];
            numberOfDownloadedFile = 0;
            [TestFlight passCheckpoint:[NSString stringWithFormat:@"Ready to save %d images", listSelected.count]];
            for (NSNumber * index in listSelected) {
                Items * item = (Items*)[imageListArray objectAtIndex:[index intValue]];
                [item setField4:[Utilities uniqueStringWithPrefix:@""]];
                [[(AppDelegate*)[[UIApplication sharedApplication] delegate] dataManager] updateAnItem:item inEntityWithName:@"ManagedItems"];
                
                NSString * originalFileName = [item.image lastPathComponent];
                NSURL * fileURL = [NSURL URLWithString:item.image];
                NSString * newFileName = [NSString stringWithFormat:@"F%@", originalFileName];
                newFileName = [NSString stringWithFormat:@"%@_%@.png", [Utilities uniqueStringWithPrefix:@"F"], [[originalFileName componentsSeparatedByString:@"_"] objectAtIndex:1]];
                
                if (![Utilities checkFavoriteAdded:originalFileName]) {
                    DownloadHelper * downloadHelper = [[DownloadHelper alloc] init];
                    [downloadHelper setMethod:DOWNLOAD_IMAGE_AT_IMAGEVIEWDETAIL];
                    [downloadHelper downloadFile:newFileName toFolderWithName:@"Favorites" withURL:fileURL andNotification:originalFileName];
                    numberOfDownloadedFile++;
                    NSLog(@"File RUL: %@", fileURL.absoluteString);
                    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadFinished:) name:originalFileName object:nil];
                    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadFailed:) name:@"failrequest" object:nil];
                }
                
            }
            if (numberOfDownloadedFile == 0) {
                [[(AppDelegate*)[[UIApplication sharedApplication] delegate] loadingView] stopLoadingView];

                [gridView setFrame:CGRectMake(0, 0, 320, 368)];
                [self.navigationController setNavigationBarHidden:NO animated:NO];
                [saveMultiToolBar setHidden:YES];
                [gridView reloadData];
            }
            break;
            
        default:
            break;
    }
}

#pragma mark - Downloading To Favorites Folder Notification

- (void)downloadFinished:(NSNotification*)notifier
{
    NSLog(@"DownloadFinish:%@",notifier.name);
    if (isDownloadedByPopup) {
        if (![[(Items*)[imageListArray objectAtIndex:selectedCellIndex] image] isEqualToString: notifier.name]) {
            return;
        }
        NSLog(@"selected btn:%d",popupBtnTagClicked);
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.image = [self imageAtIndex:selectedCellIndex];
        isDownloadedByPopup=NO;
        isDownloaded=DownloadSuccess;

        if (popupBtnTagClicked==-1) {
            return;
            
        }
        else {
            [self popupDidSelectBtnTag:popupBtnTagClicked];
        }
        
        return;
    }
    numberOfDownloadedFile--;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:notifier.name object:nil];
    if (numberOfDownloadedFile == 0) {
        [[(AppDelegate*)[[UIApplication sharedApplication] delegate] loadingView] stopLoadingView];

        [gridView setFrame:CGRectMake(0, 0, 320, 368)];
        [self.navigationController setNavigationBarHidden:NO animated:NO];
        [saveMultiToolBar setHidden:YES];
        [gridView reloadData];
        for (int i = 0; i < imageListArray.count; i++){
            [listOfFlags addObject:@"0"];
        }
    }
    [TestFlight passCheckpoint:@"Save Multiple successfully"];
    NSLog(@"Save Multiple successfully");
}

- (void)downloadFailed:(NSNotification*)notifier
{
    NSLog(@"DownloadFailed");
    if (isDownloadedByPopup) {
//        [[(AppDelegate*)[[UIApplication sharedApplication] delegate] loadingView] stopLoadingView];
        isDownloadedByPopup = NO;
        isDownloaded = DownloadFailed;
        return;
    }
    
    numberOfDownloadedFile--;
    if (numberOfDownloadedFile == 0) {
        [[(AppDelegate*)[[UIApplication sharedApplication] delegate] loadingView] stopLoadingView];
        [gridView setFrame:CGRectMake(0, 0, 320, 368)];
        [self.navigationController setNavigationBarHidden:NO animated:NO];
        [saveMultiToolBar setHidden:YES];
        [gridView reloadData];
        for (int i = 0; i < imageListArray.count; i++)
            [listOfFlags addObject:@"0"];
    }
    [TestFlight passCheckpoint:@"Save Multiple fail"];
    NSLog(@"Save multiple failed: %@", [((NSError*)notifier.object) description]);
}

#pragma mark - Grid View Data Source

- (NSString*)gridView:(UIGridView *)gridView imageURLStringOfCellAtIndex:(NSInteger)cellIndex
{
    return ((Items*)[imageListArray objectAtIndex:cellIndex]).image;
}

- (CGFloat)gridView:(UIGridView *)gridView heightForRowAtIndex:(NSInteger)rowIndex
{
    return 100;
}

- (NSInteger)numberOfCellsInGridView:(UIGridView *)gridView
{
    return [imageListArray count];
}

- (NSInteger)gridView:(UIGridView *)gridView numberOfCellsPerRowInRow:(NSInteger)rowIndex
{
    return 3;
}

- (GridViewCell*)gridView:(UIGridView *)gridView cellAtIndex:(NSInteger)cellIndex
{
    UIGridViewCell_DownloadImage * cell = [[[UIGridViewCell_DownloadImage alloc] initWithFrame:CGRectZero] autorelease];
    
    if ([imageListArray count] == 0) {
        return nil;
    }
    Items * item = [imageListArray objectAtIndex:cellIndex];
    NSLog(@"ItemCreateDate[%d]%@",cellIndex,item.created_date);
    [cell setImageURLString:item.field3];    
    [cell.imageView setContentMode:UIViewContentModeScaleAspectFit];
    [cell.textLabel setHidden:YES];
    if (isMultipleSelection) {
        if ([[listOfFlags objectAtIndex:cellIndex] isEqualToString:@"1"]) {
            [cell setAccessoryType:UIGridViewCellAccessorySelected];
            [cell setIsSelected:YES];
        }
        else {
            [cell setAccessoryType:UIGridViewCellAccessoryNone];
            [cell setIsSelected:NO];
        }
    }
    else
        [cell setAccessoryType:UIGridViewCellAccessoryNone];
    
    return cell;
}

#pragma mark - Grid View Delegate


- (void)gridView:(UIGridView *)_gridView didSelectedCellAtIndex:(NSInteger)cellIndex
{
    if (!isMultipleSelection) 
    {   //  If single select mode, push to ImageDetailViewController
        
        if (![self imageAtIndex:cellIndex]) {
            NSLog(@"Download:%@",[(Items*)[imageListArray objectAtIndex:cellIndex] image]);
            DownloadHelper * downloadHelper = [[DownloadHelper alloc] init];
            [downloadHelper setMethod:DOWNLOAD_IMAGE_AT_IMAGEVIEWDETAIL];
            [downloadHelper downloadFile:[[(Items*)[imageListArray objectAtIndex:cellIndex] image] lastPathComponent] 
                                 withURL:[NSURL URLWithString:[(Items*)[imageListArray objectAtIndex:cellIndex] image]] 
                     andNotificationName:[(Items*)[imageListArray objectAtIndex:cellIndex] image]];
            
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadFinished:) name:[(Items*)[imageListArray objectAtIndex:cellIndex] image] object:nil];
            
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadFailed:) name:@"failrequest" object:nil];
            isDownloadedByPopup=YES;
            isDownloaded =DownloadProcessing;

        }
        else {
            NSLog(@"File Exist!");
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            pasteboard.image = [self imageAtIndex:cellIndex];
            isDownloadedByPopup=NO;
            isDownloaded = DownloadSuccess;
        }
        
        Items *item=[imageListArray objectAtIndex:cellIndex];
        [item setField5:[Utilities uniqueStringWithPrefix:@""]];
        [[(AppDelegate*)[[UIApplication sharedApplication] delegate] dataManager] updateAnItem:item 
                                                                              inEntityWithName:@"ManagedItems"];
        
        CGPoint offsetPoint = gridView.contentOffset;
        NSLog(@"offset point: %f, %f", offsetPoint.x, offsetPoint.y);
        
        CGRect frame = [[gridView cellAtIndex:cellIndex] frame];
        
        [popUpBar setSelectedFrame:CGRectMake(frame.origin.x - offsetPoint.x, 
                                              frame.origin.y - offsetPoint.y, 
                                              frame.size.width, 
                                              frame.size.height)];
        
        if ([Utilities checkFavoriteAdded:[[(Items*)[imageListArray objectAtIndex:cellIndex] image] lastPathComponent]]) {
            [popUpBar.addToFavoriteButton setImage:[UIImage imageNamed:@"option_bar_btn.png"] 
                                          forState:UIControlStateNormal];

        }
        else {
            [popUpBar.addToFavoriteButton setImage:[UIImage imageNamed:@"option_bar_empty_btn.png"] 
                                          forState:UIControlStateNormal];

        }

        
        if (selectedCellIndex == cellIndex)
        {
            [popUpBar.view setHidden:!popUpBar.view.hidden];
        }
        else {
            [popUpBar.view setHidden:NO];
        }
        selectedCellIndex = cellIndex;
        popupBtnTagClicked=-1;
        
        [self.view bringSubviewToFront:popupLabel];
        [popupLabel setHidden:NO];
        [popupLabel performSelector:@selector(setHidden:) withObject:[NSNumber numberWithInt:1] afterDelay:3];
        
    }
    else 
    {   //  If multiple select mode, 
        [listSelected addObject:[NSNumber numberWithInt:cellIndex]];
        NSLog(@"cellIndex: %d", cellIndex);
        if ([listSelected count]==0) {
            [saveBtn setEnabled:NO];
        }
        else {
            [saveBtn setEnabled:YES];
        }
        
        if ([[listOfFlags objectAtIndex:cellIndex] isEqualToString:@"1"]) {
            [listOfFlags replaceObjectAtIndex:cellIndex withObject:@"0"];
        }
        else{
            [listOfFlags replaceObjectAtIndex:cellIndex withObject:@"1"];
        }
        int count=0;
        for (int i=0; i<listOfFlags.count; i++) {
            if ([[listOfFlags objectAtIndex:i] isEqualToString:@"1"]) {
                count++;
            }
        }
        [textlb setTitle:[NSString stringWithFormat:@"%d Photos Selected",count]];
    }
}

- (void)gridView:(UIGridView*)gridView didLongPressCellAtIndex:(NSInteger)cellIndex
{
    
}

- (void)gridViewDidScroll:(UIGridView *)gridView
{
    // Hide pop up menu when scrolling
    if (!popUpBar.view.hidden) {
        [popUpBar.view setHidden:YES];
    }
}

#pragma mark -

-(void)resetListOfFlags{

}

#pragma mark - Pop Up Bar Delegate

- (void)popUpBar:(PopUpViewController *)popUpController didSelectButton:(id)sender
{
//    [[(AppDelegate*)[[UIApplication sharedApplication] delegate] loadingView] showLoadingView];

    NSLog(@"image isdownloaded:%d",isDownloaded);
    
    if (isDownloaded==DownloadSuccess || [sender tag]==2
        ||([sender tag]==1 && 
           [Utilities checkFavoriteAdded:[[(Items*)[imageListArray objectAtIndex:selectedCellIndex] image] lastPathComponent]])) {
        [self popupDidSelectBtnTag:[sender tag]];
    }
    else {
        popupBtnTagClicked=[sender tag];
    }
    
    [popUpBar.view setHidden:YES];
}

-(void)popupDidSelectBtnTag:(int)tag{
    [[(AppDelegate*)[[UIApplication sharedApplication] delegate] loadingView] stopLoadingView];
    
    NSLog(@"popupDidSelectBtnTag:%d",tag);
    copyLabel.hidden=NO;
    copyLabel.text=@"Image Copied!";
    ImageDetailViewController * detailView;
    switch (tag) {
        case 0:
            NSLog(@"Share");
            NSString *stringURL = @"sms:";
            NSURL *url = [NSURL URLWithString:stringURL];
            [[UIApplication sharedApplication] openURL:url]; 
            break;
            
        case 1:

            if ([Utilities checkFavoriteAdded:[[(Items*)[imageListArray objectAtIndex:selectedCellIndex] image] lastPathComponent]]) {
                [popUpBar.addToFavoriteButton setImage:[UIImage imageNamed:@"option_bar_empty_btn.png"] forState:UIControlStateNormal];
                
                NSLog(@"Remove from Favorites:%d",selectedCellIndex);
                NSString *documentPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                NSString *favoritePath=[documentPath stringByAppendingPathComponent:@"Favorites"];
                NSFileManager *fm=[[[NSFileManager alloc] init] autorelease];     
                NSArray *favoriteList=[fm contentsOfDirectoryAtPath:favoritePath error:nil];
                
                //remove from recently added
                Items * item = [imageListArray objectAtIndex:selectedCellIndex];
                
                [item setField4:@"19990102030405"];
                
                [[(AppDelegate*)[[UIApplication sharedApplication] delegate] dataManager] updateAnItem:item 
                                                                                      inEntityWithName:@"ManagedItems"];
                
                
                //find item
                for (NSString *item in favoriteList) {
                    if ([[[[[(Items*)[imageListArray objectAtIndex:selectedCellIndex] image] lastPathComponent] componentsSeparatedByString:@"_"] objectAtIndex:1] 
                         isEqualToString:
                         [[[[item componentsSeparatedByString:@"_"] objectAtIndex:1] componentsSeparatedByString:@"."] objectAtIndex:0]]) {
                        //remove item
                        [fm removeItemAtPath:[favoritePath stringByAppendingPathComponent:item] error:nil];
                        return;
                    }
                }
            }
            else {
                [popUpBar.addToFavoriteButton setImage:[UIImage imageNamed:@"option_bar_btn.png"] forState:UIControlStateNormal];

                NSLog(@"Add to Favorites....:%d",selectedCellIndex);
                Items * item = [imageListArray objectAtIndex:selectedCellIndex];
                
                [item setField4:[Utilities uniqueStringWithPrefix:@""]];
                
                [[(AppDelegate*)[[UIApplication sharedApplication] delegate] dataManager] updateAnItem:item 
                                                                                      inEntityWithName:@"ManagedItems"];
                
                UtilityMethodStatus saving=[Utilities saveFileAtDocumentWithName:[item.image lastPathComponent] toSubFolder:@"Favorites" andNewName:[Utilities uniqueStringWithPrefix:@"F"]];
                NSLog(@"Add to Favorites Finish:%d",saving);
            }

            
            break;
            
        case 2:
            NSLog(@"View detail");
            detailView = [[ImageDetailViewController alloc] init];
            [detailView setItemList:imageListArray];
            [detailView setItemIndex:selectedCellIndex];
            [detailView setItemType:@"item"];
            [self.navigationController pushViewController:detailView animated:YES];
            [detailView release];
            break;
            
        default:
            break;
    }
    if (tag==3) {
        MemeCreatorViewController *mcvc=[[MemeCreatorViewController alloc] init];
        [mcvc setImage:[self imageAtIndex:selectedCellIndex]];
        [self presentModalViewController:mcvc animated:YES];
    }
}
#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if ([actionSheet tag]==0) {
        if (buttonIndex==0) {
            
            [gridView setFrame:CGRectMake(0, 0, 320, 368)];
            isMultipleSelection = NO;
            UIImageWriteToSavedPhotosAlbum([self imageAtIndex:selectedCellIndex], nil,nil,nil);
            return;
        }
        if (buttonIndex==1) {
            
//            [self sendMail];
            
            
            return;
        }
    }
}

- (UIImage *)imageAtIndex:(NSUInteger)index {
    
    NSLog(@"ImageListViewController - imageAtIndex:%d",index);
    Items *item = [imageListArray objectAtIndex:index];
    
    NSString *documentPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSFileManager *fm=[[NSFileManager alloc] init];
    if ([fm fileExistsAtPath:documentPath]) {
        return [UIImage imageWithContentsOfFile:[documentPath stringByAppendingPathComponent:[[item image] lastPathComponent]]];
    }
    else {
        return nil;
    }
}



@end
